<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RIP仿真 WebSocket 测试工具</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2/lib/stomp.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        h1 {
            color: #333;
            border-bottom: 2px solid #4CAF50;
            padding-bottom: 10px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        input, select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .btn-danger {
            background-color: #f44336;
        }
        .btn-danger:hover {
            background-color: #da190b;
        }
        .status {
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
            font-weight: bold;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .status.connecting {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        .messages {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 15px;
            max-height: 400px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
        .message {
            margin-bottom: 10px;
            padding: 8px;
            background-color: white;
            border-left: 3px solid #4CAF50;
            border-radius: 3px;
        }
        .message.error {
            border-left-color: #f44336;
            background-color: #ffebee;
        }
        .message.info {
            border-left-color: #2196F3;
            background-color: #e3f2fd;
        }
        .timestamp {
            color: #666;
            font-size: 10px;
        }
        .route-table {
            margin-top: 10px;
            padding: 10px;
            background-color: #f0f0f0;
            border-radius: 4px;
        }
        .route-entry {
            padding: 5px;
            margin: 3px 0;
            background-color: white;
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <h1>RIP仿真 WebSocket 测试工具</h1>
    
    <div class="container">
        <h2>连接配置</h2>
        <div class="form-group">
            <label for="serverUrl">服务器地址:</label>
            <input type="text" id="serverUrl" value="http://localhost:8086" placeholder="http://localhost:8086">
        </div>
        <div class="form-group">
            <label for="simulationId">仿真ID:</label>
            <input type="text" id="simulationId" value="1" placeholder="输入仿真ID">
        </div>
        <div class="form-group">
            <label for="routerId">路由器ID:</label>
            <input type="text" id="routerId" value="R1" placeholder="输入路由器ID (如: R1, R2)">
        </div>
        <div class="form-group">
            <button id="connectBtn" onclick="connect()">连接</button>
            <button id="disconnectBtn" onclick="disconnect()" disabled class="btn-danger">断开连接</button>
            <button onclick="clearMessages()">清空消息</button>
        </div>
        <div id="status" class="status disconnected">未连接</div>
    </div>

    <div class="container">
        <h2>接收到的消息</h2>
        <div id="messages" class="messages"></div>
    </div>

    <script>
        let stompClient = null;
        let subscription = null;

        function updateStatus(status, message) {
            const statusDiv = document.getElementById('status');
            statusDiv.className = 'status ' + status;
            statusDiv.textContent = message;
        }

        function addMessage(message, type = 'info') {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ' + type;
            
            const timestamp = new Date().toLocaleTimeString();
            messageDiv.innerHTML = `
                <div class="timestamp">[${timestamp}]</div>
                <div>${message}</div>
            `;
            
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function clearMessages() {
            document.getElementById('messages').innerHTML = '';
        }

        function connect() {
            const serverUrl = document.getElementById('serverUrl').value;
            const simulationId = document.getElementById('simulationId').value;
            const routerId = document.getElementById('routerId').value;

            if (!serverUrl || !simulationId || !routerId) {
                alert('请填写所有字段');
                return;
            }

            // SockJS需要HTTP/HTTPS URL，会自动处理WebSocket连接
            // 确保URL格式正确
            let baseUrl = serverUrl.trim();
            if (!baseUrl.startsWith('http://') && !baseUrl.startsWith('https://')) {
                baseUrl = 'http://' + baseUrl;
            }
            // 移除末尾的斜杠（如果有）
            baseUrl = baseUrl.replace(/\/$/, '');
            
            const socket = new SockJS(baseUrl + '/ws');
            stompClient = Stomp.over(socket);
            
            addMessage(`正在连接到: ${baseUrl}/ws`, 'info');

            // 禁用连接按钮
            document.getElementById('connectBtn').disabled = true;
            updateStatus('connecting', '正在连接...');

            stompClient.connect({}, function(frame) {
                updateStatus('connected', '已连接');
                addMessage('WebSocket连接成功！', 'info');
                addMessage('连接帧: ' + JSON.stringify(frame), 'info');

                // 订阅路由表更新主题
                const topic = `/topic/simulations/${simulationId}/routers/${routerId}/routing-table`;
                addMessage(`订阅主题: ${topic}`, 'info');

                subscription = stompClient.subscribe(topic, function(message) {
                    try {
                        const data = JSON.parse(message.body);
                        addMessage(`收到路由表更新 - 路由器: ${data.routerId}`, 'info');
                        
                        // 显示路由表详情
                        let routeTableHtml = '<div class="route-table"><strong>路由表内容:</strong><br>';
                        if (data.routes && data.routes.length > 0) {
                            data.routes.forEach(route => {
                                routeTableHtml += `
                                    <div class="route-entry">
                                        目标: ${route.destination} | 
                                        度量值: ${route.metric} | 
                                        下一跳: ${route.nextHop || 'N/A'} | 
                                        更新时间: ${route.lastUpdated || 'N/A'}
                                    </div>
                                `;
                            });
                        } else {
                            routeTableHtml += '<div>路由表为空</div>';
                        }
                        routeTableHtml += '</div>';
                        
                        const messageDiv = document.createElement('div');
                        messageDiv.className = 'message info';
                        const timestamp = new Date().toLocaleTimeString();
                        messageDiv.innerHTML = `
                            <div class="timestamp">[${timestamp}]</div>
                            <div>${routeTableHtml}</div>
                            <pre style="margin-top: 10px; font-size: 10px;">${JSON.stringify(data, null, 2)}</pre>
                        `;
                        document.getElementById('messages').appendChild(messageDiv);
                        document.getElementById('messages').scrollTop = document.getElementById('messages').scrollHeight;
                    } catch (e) {
                        addMessage('解析消息失败: ' + e.message + '\n原始消息: ' + message.body, 'error');
                    }
                });

                document.getElementById('disconnectBtn').disabled = false;
            }, function(error) {
                updateStatus('disconnected', '连接失败');
                addMessage('连接失败: ' + error, 'error');
                document.getElementById('connectBtn').disabled = false;
            });
        }

        function disconnect() {
            if (subscription) {
                subscription.unsubscribe();
                subscription = null;
                addMessage('已取消订阅', 'info');
            }

            if (stompClient !== null) {
                stompClient.disconnect();
                addMessage('WebSocket连接已断开', 'info');
            }

            updateStatus('disconnected', '未连接');
            document.getElementById('connectBtn').disabled = false;
            document.getElementById('disconnectBtn').disabled = true;
            stompClient = null;
        }

        // 页面卸载时断开连接
        window.addEventListener('beforeunload', function() {
            disconnect();
        });
    </script>
</body>
</html>
